<?php
/**
 * Created by PhpStorm.
 * User: von
 * Date: 2017/11/24
 * Time: 15:11
 */
namespace common\models;

use common\models\MessageUserGroup;
use common\models\Responses;
use yii\db\ActiveRecord;

class InstationMessage extends ActiveRecord {


    public static function tableName()
    {
        return 'instation_message';
    }

    /**
     * 保存数据
     *  @param $param   保存数据
     * @param $data   保存数据
     */
    public static function saveMessage($param,$data){
        //条件
        $where_sender = !empty($param['where_sender'])?$param['where_sender']:0;
        $where_is_package = !empty($param['where_is _package'])?$param['where_is_package']:0;
        $where_package_project_id = !empty($param['where_package_project_id'])?$param['where_package_project_id']:0;
        $where_message_group = !empty($param['where_message_group'])?$param['where_message_group']:0;
        //添加 / 修改数据
        $sender             = !empty($data['sender'])?$data['sender']:0;    //发件人id
        $package_project_id = !empty($data['package_project_id'])?$data['package_project_id']:0;  //资产包id
        $is_package            = !empty($data['is_package'])?$data['is_package']:0;  //是否是资产包/1是资产包/2是项目
        $message_val        = !empty($data['message_val'])?$data['message_val']:json_encode('');  //消息内容 json

        $user_id            = !empty($data['user_id'])?$data['user_id']:0;  //收件人id
        $message_state      = !empty($data['message_state'])?$data['message_state']:0; //消息状态 0未阅读 1已阅读
        $message_group      = !empty($data['message_group'])?$data['message_group']:0; //消息分类 1待审批提醒 2审批反馈 3关注更新
        $message_read_IP      = ip2long(\Yii::$app->request->userIP);
        //保存数据
        $messageModel = '';
        $messageId = 0;
        $transaction=\Yii::$app->db->beginTransaction();
        try{
            if (!empty($where_sender) && !empty($where_is_package) && !empty($where_package_project_id)){
                $messageModel = InstationMessage::find()->where(['sender'=>$where_sender,'is_package'=>$where_is_package,'package_project_id'=>$where_package_project_id,'message_group'=>$where_message_group])->one();
                $messageId = $messageModel['id'];
            }
            if (empty($messageModel)){
                $messageModel = new InstationMessage();
            }
            $messageModel->package_project_id=$package_project_id;
            $messageModel->message_val  =$message_val;
            $messageModel->is_package   =$is_package;
            $messageModel->sender        =$sender;
//            $messageModel->message_start_time  = date('Y-m-d H:i:s',time());
            $messageModel->message_group        =$message_group;
            $messageState = $messageModel->save(false);
            if (empty($messageId)){
                $messageId    = $messageModel->attributes['id'];  //添加数据的id
            }
            //保存表数据 message_user_group
            $is_guanzhu      = !empty($param['is_guanzhu'])?$param['is_guanzhu']:0; //消息状态 0未阅读 1已阅读
            if (!empty($is_guanzhu)){
                $MessageUserGroupModel = MessageUserGroup::findAll(['message_user_group_id'=>$messageId]);
                if (!empty($MessageUserGroupModel)){
                    MessageUserGroup::deleteAll(['message_user_group_id'=>$messageId]);
                    }
            }
            $MessageUserGroupModel = MessageUserGroup::findAll(['message_user_group_id'=>$messageId]);
            if (empty($MessageUserGroupModel)) {
                $MessageUserkey = ['user_id', 'message_user_group_id', 'message_state', 'message_group', 'message_read_IP'];
                foreach ($user_id as $k => $v) {
                    $insertMessageUserData[] = [$v, $messageId, $message_state, $message_group, $message_read_IP];
                }
                $messageUserGroupState = \Yii::$app->db->createCommand()->batchInsert(MessageUserGroup::tableName(),$MessageUserkey,$insertMessageUserData)->execute();
            }else{
                $upSql = "update message_user_group set message_state = $message_state ,message_group= $message_group,message_read_IP = $message_read_IP WHERE message_user_group_id = $messageId";
                $messageUserGroupState = \Yii::$app->db->createCommand($upSql)->query();
            }
            if ($messageState && $messageUserGroupState){
                $transaction->commit();
                return Responses::response200('',1,'发送消息成功');
            }
            $transaction->rollback();//如果操作失败, 数据回滚
            return Responses::response400('发送消息失败');
        }catch (\Exception $exception){
            $transaction->rollback();//如果操作失败, 数据回滚
            return Responses::response400('发送消息失败');
        }
    }


    /**
     * 更新数据为已读 //管理员更新所有数据
     * @param $param 条件
     */
        public static function readAdminMessage($param){
            //更新条件
            $message_user_group_id = !empty($param['message_user_group_id'])?$param['message_user_group_id']:0; //资产包id
            $transaction=\Yii::$app->db->beginTransaction();
            try{
                $ip = ip2long($_SERVER['REMOTE_ADDR']);
                $upSql = "update message_user_group set message_state = 1,message_read_IP = $ip WHERE message_user_group_id = $message_user_group_id";
                $UserMessageAllData = \Yii::$app->db->createCommand($upSql)->query();
                if ($UserMessageAllData){
                    $transaction->commit();
                    return Responses::response200(['',1,'更新数据成功']);
                }
                return Responses::response400('更新数据失败');
            }catch (\Exception $exception){
                $transaction->rollback();//如果操作失败, 数据回滚
                return Responses::response400('更新数据失败');
            }
        }
    /**
     * 更新数据为已读 //关注更新单个数据
     * @param $param 条件
     */
    public static function readLikeMessage($param){
        //更新条件
        $user_id = !empty($param['user_id'])?$param['user_id']:0; //收件人id
        $message_user_group_id = !empty($param['message_user_group_id'])?$param['message_user_group_id']:0; //资产包id
        $transaction=\Yii::$app->db->beginTransaction();
        try{
            $ip = ip2long($_SERVER['REMOTE_ADDR']);
            $upSql = "update message_user_group set message_state=1,message_read_IP = $ip WHERE message_user_group_id = $message_user_group_id AND user_id = $user_id";
            $UserMessageAllData = \Yii::$app->db->createCommand($upSql)->query();
            if ($UserMessageAllData){
                $transaction->commit();
                return Responses::response200(['',1,'更新数据成功']);
            }
            return Responses::response400('更新数据失败');
        }catch (\Exception $exception){
            $transaction->rollback();//如果操作失败, 数据回滚
            return Responses::response400('更新数据失败');
        }
    }

    /**
     * 获取数据
     * @param $user_id 收件人id
     * @param $message_state 未阅读
     * @param $message_group1 消息分类 1待审批提醒 2审批反馈 3关注更新
     * @param int $is_package 是否为资产包 1资产包 2项目
     * @return array
     */
    public static function getMessage($user_id,$message_state,$message_group1,$is_package=0,$message_group2=0){
        if (empty($is_package)){
            $where_is_package = [];
        }else{
            $where_is_package = ['=','im.is_package',$is_package];
        }
        $whereMessageGroup = ['or',['=','mug.message_group',$message_group1],['=','mug.message_group',$message_group2]];
        if (!empty($user_id) && !empty($message_state) && !empty($message_group1)){
            $messageModel = (new \yii\db\Query())->from('instation_message as im')->leftJoin('message_user_group as mug','im.id = mug.message_user_group_id')->where($where_is_package)->andwhere(['=','mug.user_id',$user_id])->andWhere(['=','mug.message_state',$message_state])->andWhere($whereMessageGroup);
            $messageData = $messageModel->all();
            $messageCount = $messageModel->count();
            if ($messageData){
                return Responses::response200($messageData,$messageCount,'获取信息成功');
            }
        }
        return Responses::response400('获取信息失败');
    }

}
